/*
 * @Date: 2023-01-14 21:59:47
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-20 17:09:34
 * @FilePath: \A19\backend\src\api\Search\ApiSearchCourses.ts
 */
import { Global } from './../../Global/index';
import { ApiCall } from "tsrpc";
import { ReqSearchCourses, ResSearchCourses } from "../../shared/protocols/Search/PtlSearchCourses";
import { courses } from '../../shared/types/courses';

export default async function (call: ApiCall<ReqSearchCourses, ResSearchCourses>) {
    // TODO
    const user = call.currentUser
    const name = call.req.name

    // const courses = await Global.collection('courses').find({
    //     name: {
    //         $regex: new RegExp(name)
    //     },
    //     school: user.school
    // }).toArray()
    const couresDocs = await Global.collection('courses').aggregate([
        {
            $match: {
                name: {
                    $regex: new RegExp(name)
                },
                // school: user.school
            }
        },
        {
            $lookup: {
                from: 'users',
                localField: 'teacher',
                foreignField: '_id',
                as: "teacher"
            }
        },
        {
            $project: {
                'teacher.password': false,
                // 'teacher.role': false,
                // 'teacher.email': false,
                // 'teacher.school': false,
                // 'teacher.number': false,
                // 'teacher.gender': false,
                // 'teacher.portrait': false,
            }
        }
    ]).toArray()
    const courses:any[] = couresDocs.map(doc => {
        if (doc.teacher.length > 0) {
            return {
                ...doc,
                teacher: doc.teacher[0]
            }
        }
        else {
            return {
                ...doc,
                teacher: {
                    _id:undefined,
                    name:''
                }
            }
        }
    })
    // courses.forEach((course)=>{
    //     console.log(course);
    // })

    call.succ({
        courses:courses
    })
}